/**
 * Mock API 工具
 * 模拟后端接口请求响应
 */

/**
 * 模拟网络延迟
 * @param {number} delay - 延迟时间（毫秒）
 * @returns {Promise}
 */
const simulateDelay = (delay = 1000) => {
  return new Promise(resolve => setTimeout(resolve, delay));
};

/**
 * 生成随机ID
 * @returns {string}
 */
const generateId = () => {
  return Date.now().toString() + Math.random().toString(36).substr(2, 9);
};

/**
 * Mock API 响应封装
 * @param {Object} data - 响应数据
 * @param {string} message - 响应消息
 * @param {number} code - 状态码
 * @returns {Object}
 */
const mockResponse = (data = null, message = 'success', code = 200) => {
  return {
    code,
    message,
    data,
    timestamp: Date.now()
  };
};

/**
 * 模拟提交家教老师订单
 * @param {Object} formData - 表单数据
 * @returns {Promise}
 */
export const submitTeacherOrder = async (formData) => {
  // 模拟网络延迟
  await simulateDelay(1500);
  
  // 模拟数据验证
  if (!formData.phone) {
    return mockResponse(null, '请填写联系电话', 400);
  }
  
  if (!formData.area) {
    return mockResponse(null, '请选择现居区域', 400);
  }
  
  if (!formData.teachingAge) {
    return mockResponse(null, '请选择教龄', 400);
  }
  
  if (!formData.subject) {
    return mockResponse(null, '请选择家教科目', 400);
  }
  
  // 模拟90%成功率
  const isSuccess = Math.random() > 0.1;
  
  if (isSuccess) {
    // 保存到本地存储（模拟数据持久化）
    const orderId = generateId();
    const orderData = {
      ...formData,
      orderId,
      status: 'pending',
      createdAt: new Date().toISOString()
    };
    
    try {
      // 获取已有订单列表
      let orders = uni.getStorageSync('teacher_orders') || [];
      orders.push(orderData);
      uni.setStorageSync('teacher_orders', orders);
    } catch (e) {
      console.error('保存订单失败:', e);
    }
    
    return mockResponse(
      { orderId, ...orderData },
      '提交成功',
      200
    );
  } else {
    return mockResponse(null, '网络错误，请重试', 500);
  }
};

/**
 * 模拟提交学生需求订单
 * @param {Object} formData - 表单数据
 * @returns {Promise}
 */
export const submitStudentOrder = async (formData) => {
  await simulateDelay(1200);
  
  const isSuccess = Math.random() > 0.1;
  
  if (isSuccess) {
    const orderId = generateId();
    const orderData = {
      ...formData,
      orderId,
      status: 'pending',
      createdAt: new Date().toISOString()
    };
    
    try {
      let orders = uni.getStorageSync('student_orders') || [];
      orders.push(orderData);
      uni.setStorageSync('student_orders', orders);
    } catch (e) {
      console.error('保存订单失败:', e);
    }
    
    return mockResponse(
      { orderId, ...orderData },
      '发布成功',
      200
    );
  } else {
    return mockResponse(null, '网络错误，请重试', 500);
  }
};

/**
 * 获取用户的订单列表
 * @param {string} type - 订单类型 'teacher' | 'student'
 * @returns {Promise}
 */
export const getOrderList = async (type = 'teacher') => {
  await simulateDelay(800);
  
  try {
    const storageKey = type === 'teacher' ? 'teacher_orders' : 'student_orders';
    const orders = uni.getStorageSync(storageKey) || [];
    
    return mockResponse(
      { list: orders, total: orders.length },
      '获取成功',
      200
    );
  } catch (e) {
    console.error('获取订单失败:', e);
    return mockResponse(null, '获取失败', 500);
  }
};

/**
 * 删除订单
 * @param {string} orderId - 订单ID
 * @param {string} type - 订单类型
 * @returns {Promise}
 */
export const deleteOrder = async (orderId, type = 'teacher') => {
  await simulateDelay(500);
  
  try {
    const storageKey = type === 'teacher' ? 'teacher_orders' : 'student_orders';
    let orders = uni.getStorageSync(storageKey) || [];
    orders = orders.filter(order => order.orderId !== orderId);
    uni.setStorageSync(storageKey, orders);
    
    return mockResponse(null, '删除成功', 200);
  } catch (e) {
    console.error('删除订单失败:', e);
    return mockResponse(null, '删除失败', 500);
  }
};

/**
 * 提交老师自我介绍信息
 * @param {string} orderId - 订单ID
 * @param {Object} introData - 自我介绍数据
 * @returns {Promise}
 */
export const submitTeacherIntro = async (orderId, introData) => {
  // 模拟网络延迟
  await simulateDelay(1200);
  
  // 模拟数据验证
  if (!introData.selfEvaluation) {
    return mockResponse(null, '请填写自我评价', 400);
  }
  
  if (!introData.teachingExperience) {
    return mockResponse(null, '请填写任教经验', 400);
  }
  
  if (!introData.certificateDescription) {
    return mockResponse(null, '请填写证书描述', 400);
  }
  
  // 模拟90%成功率
  const isSuccess = Math.random() > 0.1;
  
  if (isSuccess) {
    try {
      // 更新订单数据
      let orders = uni.getStorageSync('teacher_orders') || [];
      const orderIndex = orders.findIndex(order => order.orderId === orderId);
      
      if (orderIndex > -1) {
        // 订单存在，更新数据
        orders[orderIndex] = {
          ...orders[orderIndex],
          ...introData,
          introSubmittedAt: new Date().toISOString(),
          status: 'intro_completed' // 更新状态
        };
        uni.setStorageSync('teacher_orders', orders);
        
        return mockResponse(
          { orderId, ...orders[orderIndex] },
          '提交成功',
          200
        );
      } else {
        // 订单不存在，创建新的（兼容没有orderId的情况）
        const newOrderId = orderId || generateId();
        const orderData = {
          orderId: newOrderId,
          ...introData,
          introSubmittedAt: new Date().toISOString(),
          status: 'intro_completed',
          createdAt: new Date().toISOString()
        };
        orders.push(orderData);
        uni.setStorageSync('teacher_orders', orders);
        
        return mockResponse(
          orderData,
          '提交成功',
          200
        );
      }
    } catch (e) {
      console.error('保存自我介绍失败:', e);
      return mockResponse(null, '保存失败', 500);
    }
  } else {
    return mockResponse(null, '网络错误，请重试', 500);
  }
};

/**
 * 提交老师认证信息
 * @param {string} orderId - 订单ID
 * @param {Object} certData - 认证数据
 * @returns {Promise}
 */
export const submitTeacherCertification = async (orderId, certData) => {
  await simulateDelay(1500);
  
  const isSuccess = Math.random() > 0.1;
  
  if (isSuccess) {
    try {
      let orders = uni.getStorageSync('teacher_orders') || [];
      const orderIndex = orders.findIndex(order => order.orderId === orderId);
      
      if (orderIndex > -1) {
        orders[orderIndex] = {
          ...orders[orderIndex],
          ...certData,
          certSubmittedAt: new Date().toISOString(),
          status: 'completed' // 最终完成状态
        };
        uni.setStorageSync('teacher_orders', orders);
        
        return mockResponse(
          { orderId, ...orders[orderIndex] },
          '提交成功，等待审核',
          200
        );
      } else {
        return mockResponse(null, '订单不存在', 404);
      }
    } catch (e) {
      console.error('保存认证信息失败:', e);
      return mockResponse(null, '保存失败', 500);
    }
  } else {
    return mockResponse(null, '网络错误，请重试', 500);
  }
};

/**
 * 获取老师详情
 * @param {string} teacherId - 老师ID
 * @returns {Promise}
 */
export const getTeacherDetail = async (teacherId) => {
  await simulateDelay(800);
  
  try {
    // 从本地JSON文件加载老师详情
    return new Promise((resolve, reject) => {
      uni.request({
        url: '/static/data/teacher-detail.json',
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            // 根据teacherId查找对应的老师
            const teacher = res.data.teachers.find(t => t.id == teacherId);
            
            if (teacher) {
              resolve(mockResponse(teacher, '获取成功', 200));
            } else {
              resolve(mockResponse(null, '老师不存在', 404));
            }
          } else {
            reject(mockResponse(null, '获取失败', 500));
          }
        },
        fail: (err) => {
          console.error('获取老师详情失败:', err);
          reject(mockResponse(null, '网络错误', 500));
        }
      });
    });
  } catch (e) {
    console.error('获取老师详情异常:', e);
    return mockResponse(null, '获取失败', 500);
  }
};

/**
 * 获取学生需求详情
 * @param {string} studentId - 学生需求ID
 * @returns {Promise}
 */
export const getStudentDetail = async (studentId) => {
  await simulateDelay(800);
  
  try {
    // 从本地JSON文件加载学生需求详情
    return new Promise((resolve, reject) => {
      uni.request({
        url: '/static/data/student-detail.json',
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            // 根据studentId查找对应的需求
            const student = res.data.students.find(s => s.id == studentId);
            
            if (student) {
              resolve(mockResponse(student, '获取成功', 200));
            } else {
              resolve(mockResponse(null, '需求不存在', 404));
            }
          } else {
            reject(mockResponse(null, '获取失败', 500));
          }
        },
        fail: (err) => {
          console.error('获取学生需求详情失败:', err);
          reject(mockResponse(null, '网络错误', 500));
        }
      });
    });
  } catch (e) {
    console.error('获取学生需求详情异常:', e);
    return mockResponse(null, '获取失败', 500);
  }
};

export default {
  submitTeacherOrder,
  submitStudentOrder,
  submitTeacherIntro,
  submitTeacherCertification,
  getOrderList,
  deleteOrder,
  getTeacherDetail,
  getStudentDetail
};

